package com.hyfrogx.modules.app.controller.course;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.exception.ServiceException;
import com.hyfrogx.common.utils.QueryExt;
import com.hyfrogx.common.utils.R;
import com.hyfrogx.modules.app.annotation.Login;
import com.hyfrogx.modules.app.form.course.BuyCourseForm;
import com.hyfrogx.modules.app.form.course.RemarkCourseForm;
import com.hyfrogx.modules.app.form.course.WatchCourseForm;
import com.hyfrogx.modules.app.utils.FrogxTaskCode;
import com.hyfrogx.modules.manage.controller.BaseController;
import com.hyfrogx.modules.manage.entity.course.*;
import com.hyfrogx.modules.manage.service.course.*;
import com.hyfrogx.modules.manage.service.task.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 罗春杰-技术部
 */

@RestController
@RequestMapping(value="api/Course")
@Api(value = "ApiCourseController",tags = {"客户端-课程管理"})

public class ApiCourseController extends BaseController {

    @Autowired
    private CourseOrderService orderService;

    @Autowired
    private CourseManageRemarkService remarkService;

    @Autowired
    private CourseManageSectionWatchService watchService;

    @Autowired
    private CourseManageService manageService;

    @Autowired
    private CourseManageSectionService sectionService;

    @Autowired
    private TaskService taskService;

    private static Lock lock = new ReentrantLock();

    // 接受客户订单信息创建订单
    @Login
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ApiOperation("接受客户订单信息创建订单")
    public R insertCourseOrder(@ApiIgnore @RequestAttribute("userId") Long uid, @Validated @RequestBody BuyCourseForm form) {
        lock.lock();
        try {
            if (uid == null) {
                return R.error("购买用户必填");
            }
            CourseOrderEntity order = new CourseOrderEntity();
            BeanUtils.copyProperties(form,order);
            order.setUid(uid);

            if (orderService.createCourseOrder(order) != 1) {
                return R.error("订单创建失败");
            }
            return R.ok("订单已创建");

        } catch (Exception e) {
            return R.error(e.getMessage());
        } finally {
            lock.unlock();
        }
    }

    /**
     * 查看已经被购买过课程
     */
    @Login
    @RequestMapping(value = "getpayCourseinfobyid", method = RequestMethod.POST)
    @ApiOperation("查看已经被购买过课程")
    public R getpayCourseinfobyid(@ApiIgnore @RequestAttribute("userId") Integer uid) {
        try {
            Map map = new HashMap();
            map.put("uid",uid);
            Page page = orderService.getpayCourseInfoByid(new QueryExt(map));
            return R.ok().put("data", page);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }

    }

    /**
     * 我也要评论
     */
    @Login
    @RequestMapping(value = "createRemark", method = RequestMethod.POST)
    @ApiOperation("我也要评论")
    public R  createRemark(@RequestBody RemarkCourseForm form,
                           @ApiIgnore @RequestAttribute(value = "userIp") String userIp,
                           @ApiIgnore @RequestAttribute("userId") Long uid
    ) {
        try {
            CourseManageRemarkEntity remark = new CourseManageRemarkEntity();
            BeanUtils.copyProperties(form,remark);

            remark.setCreateUid(uid);
            remark.setRemoteAddr(userIp);
            remark.setCreateTime(new Date());

            remarkService.save(remark);
            taskService.taskRemark(uid, FrogxTaskCode.TaskCode.REMARK_COURSE, remark.getCourseId());
            return R.ok("评论成功");
        } catch (ServiceException e) {
            return R.ok("评论成功");
        }catch (Exception e){
            return R.error(e.getMessage());
        }
    }

    /**
     * 覆盖上次的观看比例
     */
    @Login
    @RequestMapping(value = "updateSectionWatch", method = RequestMethod.POST)
    @ApiOperation("覆盖上次的观看比例")
    public R updateSectionWatch(@RequestBody WatchCourseForm form, @ApiIgnore @RequestAttribute("userId") Integer uid) {
        lock.lock();
        try {
            CourseManageSectionWatchEntity sectionWatch = new CourseManageSectionWatchEntity();
            BeanUtils.copyProperties(form,sectionWatch);
            sectionWatch.setUid(uid);
            CourseManageSectionWatchEntity watch = watchService.getOne(new QueryWrapper<CourseManageSectionWatchEntity>()
                    .eq("uid", sectionWatch.getUid()).eq("cid", sectionWatch.getCid()));
            CourseManageEntity courseManage = manageService.getCourseById(sectionWatch.getCid());
            if (watch != null) {
                watch.setWatch(sectionWatch.getWatch());
                watch.setUpdateDate(new Date());
                watchService.updateById(watch);
                return R.ok("覆盖成功");
            } else {
                sectionWatch.setPid(courseManage.getId());
                sectionWatch.setUpdateDate(new Date());
                watchService.save(sectionWatch);
                return R.ok("新建观看比例成功");
            }

        } catch (Exception e) {
            return R.error(e.getMessage());
        } finally {
            lock.unlock();
        }

    }

}
